package com.lanbu.system.service.impl;

import java.security.SecureRandom;
import java.util.*;
import java.util.stream.Collectors;
import javax.validation.Validator;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.lanbu.common.config.KnowledgeProperties;
import com.lanbu.common.constant.DeptConstants;
import com.lanbu.common.constant.FastGptUserConstants;
import com.lanbu.common.core.domain.entity.SysDept;
import com.lanbu.common.utils.DateUtils;
import com.lanbu.system.domain.*;
import com.lanbu.system.domain.mongo.*;
import com.lanbu.system.mapper.*;
import com.lanbu.system.service.ISysUserShareidService;
import io.lettuce.core.Limit;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.lanbu.common.annotation.DataScope;
import com.lanbu.common.constant.UserConstants;
import com.lanbu.common.core.domain.entity.SysRole;
import com.lanbu.common.core.domain.entity.SysUser;
import com.lanbu.common.exception.ServiceException;
import com.lanbu.common.utils.SecurityUtils;
import com.lanbu.common.utils.StringUtils;
import com.lanbu.common.utils.bean.BeanValidators;
import com.lanbu.common.utils.spring.SpringUtils;
import com.lanbu.system.service.ISysConfigService;
import com.lanbu.system.service.ISysDeptService;
import com.lanbu.system.service.ISysUserService;

/**
 * 用户 业务层处理
 *
 * @author lanbu
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;
    @Autowired
    private MongoMyUserOutlinksidsService mongoMyUserOutlinksidsService;
    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    protected Validator validator;
    @Autowired
    private  MongoTeamMembersService mongoTeamMembersService;
    @Autowired
    private  MongoUsersService mongoUsersService;
    @Autowired
    private    MongoTeamsService mongoTeamsService;

    @Autowired
    private MongoAppsRepository mongoAppsRepository;

    @Autowired
    private  KnowledgeProperties knowledgeProperties;

    @Autowired
    private   MongoOutlinksService mongoOutlinksService;
    @Autowired
    private  SysDeptShareidMapper sysDeptShareidMapper;

    @Autowired
    private ISysUserShareidService sysUserShareidService;

    @Value("${shareIdprefix}")
    private  String shareIdprefix ;
    @Value("${shareIdsuffix}")
    private  String shareIdsuffix;
    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    @Override
    public List<SysUser> selectUserListByDeptId(Long deptId) {
        return userMapper.selectUserListByDeptId(deptId);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);


        //将用户绑定到fastgpt
        buildFastGptUser(user);

        return rows;
    }
    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyz0123456789";
    private static final int LENGTH = 25;
    private static final SecureRandom random = new SecureRandom();

//    private void buildFastGptUser(SysUser user) {
//
//        // 创建用户与 fastGpt 相关联
//
//        SysDeptShareid deptShareid = sysDeptShareidMapper.selectSysDeptShareidByDeptId(user.getDeptId());
//
//        System.out.println(deptShareid);
//       //没有绑定流程控制
//        if (deptShareid == null || deptShareid.getShareid() == null || "".equals(deptShareid.getShareid())) {
//            Date now = new Date(); // 统一时间
//
//// 构建用户名和密码（使用常量提取）
//            String username = user.getUserId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR;
//            String password = SecureUtil.sha256(SecureUtil.sha256(username));
//
//            MongoUsers mongoUsers = new MongoUsers();
//            mongoUsers.setUsername(username );
//            mongoUsers.setPassword(password);
//            mongoUsers.setStatus(FastGptUserConstants.USER_STATUS);
//            //mongoUsers.setAvatar(FastGptUserConstants.USER_AVATAR);
//            mongoUsers.setPromotionRate(FastGptUserConstants.USER_PROMOTION_RATE_COMMON);
//            mongoUsers.setTimezone(FastGptUserConstants.TIME_ZONE);
//            mongoUsers.setCreateTime(DateUtils.getNowDate());
//            mongoUsers.setVersion(FastGptUserConstants.VERSION);
//            MongoUsers users = mongoUsersService.save(mongoUsers);
//
//            // 查出 root 的 teamId
////        MongoUsers root = Optional.ofNullable(mongoUsersService.findByUsername(knowledgeProperties.getRootName())).orElse(new MongoUsers());
////        MongoTeamMembers rootTeamMember = Optional.ofNullable(mongoTeamMembersService.findByUserId(root.getId())).orElse(new MongoTeamMembers());
//
//            MongoTeams teams = new MongoTeams();
//            teams.setName(user.getUserId()+"-"+user.getUserName());
//            teams.setCreateTime(DateUtils.getNowDate());
//            teams.setVersion(FastGptUserConstants.VERSION);
//
//
//            teams.setPath("");
//            teams.setPathId("twoFcjKLaZu6");
//
//            teams.setTeamId(users.getId());
//            teams.setOwnerId(String.valueOf(users.getId()));
//            teams.setUpdateTime(now);
//            teams.setCreateAt(now);
//            teams.setDefaultPermission("0");
//            teams.setAvatar("/icon/logo.svg");
//            MongoTeams mongoTeams = mongoTeamsService.save(teams);
//
//            // 将新建的用户加入 admin 团队下
//            MongoTeamMembers teamMembers = new MongoTeamMembers();
//            teamMembers.setAvatar("/imgs/avatar/GrayModernAvatar.svg");
//            teamMembers.setTeamId(mongoTeams.getId());
//            teamMembers.setUserId(users.getId());
//
//            teamMembers.setName(FastGptUserConstants.TEAM_MEMBER_NAME);
//            teamMembers.setRole(FastGptUserConstants.TEAM_MEMBER_NAME_NEW);
//            teamMembers.setStatus(FastGptUserConstants.USER_STATUS);
////        teamMembers.setCreateTime(DateUtils.getNowDate());
//            teamMembers.setDefaultTeam(true);
//            //新增
//
//            teamMembers.setUpdateTime(now);
//            teamMembers.setCreateAt(now);
//
//            //创建应用
//
//
//
//            mongoTeamMembersService.save(teamMembers);
//        }else {
//            Date now = new Date(); // 统一时间
//
//// 构建用户名和密码（使用常量提取）
//            String username = user.getUserId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR;
//            String password = SecureUtil.sha256(SecureUtil.sha256(username));
//
//            MongoUsers mongoUsers = new MongoUsers();
//            mongoUsers.setUsername(username );
//            mongoUsers.setPassword(password);
//            mongoUsers.setStatus(FastGptUserConstants.USER_STATUS);
//            //mongoUsers.setAvatar(FastGptUserConstants.USER_AVATAR);
//            mongoUsers.setPromotionRate(FastGptUserConstants.USER_PROMOTION_RATE_COMMON);
//            mongoUsers.setTimezone(FastGptUserConstants.TIME_ZONE);
//            mongoUsers.setCreateTime(DateUtils.getNowDate());
//            mongoUsers.setVersion(FastGptUserConstants.VERSION);
//            MongoUsers users = mongoUsersService.save(mongoUsers);
//
//            // 查出 root 的 teamId
//     //   MongoUsers root = Optional.ofNullable(mongoUsersService.findByUsername(knowledgeProperties.getRootName())).orElse(new MongoUsers());
////        MongoTeamMembers rootTeamMember = Optional.ofNullable(mongoTeamMembersService.findByUserId(root.getId())).orElse(new MongoTeamMembers());
//
//            MongoTeams teams = new MongoTeams();
//            teams.setName(user.getUserId()+"-"+user.getUserName());
//            teams.setCreateTime(DateUtils.getNowDate());
//            teams.setVersion(FastGptUserConstants.VERSION);
//
//
//            teams.setPath("");
//            teams.setPathId("twoFcjKLaZu6");
//
//            teams.setTeamId(users.getId());
//            teams.setOwnerId(String.valueOf(users.getId()));
//            teams.setUpdateTime(now);
//            teams.setCreateAt(now);
//            teams.setDefaultPermission("0");
//            teams.setAvatar("/icon/logo.svg");
//            MongoTeams mongoTeams = mongoTeamsService.save(teams);
//
//            // 将新建的用户加入 admin 团队下
//            MongoTeamMembers teamMembers = new MongoTeamMembers();
//            teamMembers.setAvatar("/imgs/avatar/GrayModernAvatar.svg");
//            teamMembers.setTeamId(mongoTeams.getId());
//            teamMembers.setUserId(users.getId());
//
//            teamMembers.setName(FastGptUserConstants.TEAM_MEMBER_NAME);
//            teamMembers.setRole(FastGptUserConstants.TEAM_MEMBER_NAME_NEW);
//            teamMembers.setStatus(FastGptUserConstants.USER_STATUS);
////        teamMembers.setCreateTime(DateUtils.getNowDate());
//            teamMembers.setDefaultTeam(true);
//            //新增
//
//            teamMembers.setUpdateTime(now);
//            teamMembers.setCreateAt(now);
//
//            //创建应用
//
//
//
//            mongoTeamMembersService.save(teamMembers);
//            String shareid = deptShareid.getShareid();
//
//            MongoOutlinks adminshareIdById = mongoOutlinksService.findShareIdById(shareid);
//            MongoApps mongoApps = mongoAppsRepository.findById(adminshareIdById.getAppId());
//            mongoApps.setId(null);
//            mongoApps.setTeamId(teamMembers.getTeamId());
//            mongoAppsRepository.save(mongoApps);
//            MongoOutlinks mongoOutlinks =new MongoOutlinks();
//
//            mongoOutlinks.setAppId(mongoApps.getId());
//            mongoOutlinks.setName(username+"--"+mongoApps.getName());
//            mongoOutlinks.setTeamId(teamMembers.getTeamId());
//            mongoOutlinks.setTmbId(teamMembers.getId());
//            String random = generateRandomString();
//            mongoOutlinks.setType("share");
//            mongoOutlinks.setShareId(random);
//            mongoOutlinks.setResponseDetail(true);
//            mongoOutlinks.setShowNodeStatus(true);
//            mongoOutlinks.setShowRawSource(true);
//            mongoOutlinks.setUsagePoints(0);
//
//            MongoOutlinks.Limit limit = new MongoOutlinks.Limit();
//            limit.setMaxUsagePoints(-1);
//            limit.setQPM(100);
//            mongoOutlinksService.save(mongoOutlinks);
//            SysUserShareid userShareid =new SysUserShareid();
//            userShareid.setUserId(user.getUserId());
//            userShareid.setName(user.getUserName());
//            userShareid.setShareid(random);
//            sysUserShareidService.insertSysUserShareid(userShareid);
//
//
//        }
//
//
//
//    }
private void buildFastGptUser(SysUser user) {
    String username = user.getUserId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR;
    String password = SecureUtil.sha256(SecureUtil.sha256(username));
    Date now = new Date();

    // 1. 创建 Mongo 用户
    MongoUsers mongoUser = createMongoUser(username, password, now);

    // 2. 创建 Mongo 团队
    MongoTeams mongoTeam = createMongoTeam(user, mongoUser.getId().toHexString(), now);

    // 3. 创建团队成员
    MongoTeamMembers teamMember = createTeamMember(mongoUser.getId(), mongoTeam.getId(), now);

    // 4. 绑定流程控制，如果部门未绑定流程，则跳过后续应用与分享创建
    SysDeptShareid deptShareid = sysDeptShareidMapper.selectSysDeptShareidByDeptId(user.getDeptId());
    if (deptShareid != null && StringUtils.isNotBlank(deptShareid.getShareid())) {
        try {
            cloneAndShareApp(deptShareid.getShareid(), teamMember, username, user);
        } catch (Exception e) {
            log.error("克隆应用或生成分享链接失败，userId={}, shareid={}", user.getUserId(), deptShareid.getShareid(), e);
        }
    }
}

    private MongoUsers createMongoUser(String username, String password, Date now) {
        MongoUsers user = new MongoUsers();
        user.setUsername(username);
        user.setPassword(password);
        user.setStatus(FastGptUserConstants.USER_STATUS);
        user.setPromotionRate(FastGptUserConstants.USER_PROMOTION_RATE_COMMON);
        user.setTimezone(FastGptUserConstants.TIME_ZONE);
        user.setCreateTime(now);
        user.setVersion(FastGptUserConstants.VERSION);
        return mongoUsersService.save(user);
    }

    private MongoTeams createMongoTeam(SysUser sysUser, String userId, Date now) {
        MongoTeams team = new MongoTeams();
        team.setName(sysUser.getUserId() + "-" + sysUser.getUserName());
      //  team.setTeamId(userId.toHexString());
        team.setOwnerId(userId);
        team.setPath("");
        team.setPathId("twoFcjKLaZu6");
        team.setUpdateTime(now);
        team.setCreateAt(now);
        team.setCreateTime(now);
        team.setVersion(FastGptUserConstants.VERSION);
        team.setDefaultPermission("0");
        team.setAvatar("/icon/logo.svg");
        return mongoTeamsService.save(team);
    }

    private MongoTeamMembers createTeamMember(ObjectId userId, ObjectId teamId, Date now) {
        MongoTeamMembers member = new MongoTeamMembers();
        member.setUserId(userId);
        member.setTeamId(teamId);
        member.setAvatar("/imgs/avatar/GrayModernAvatar.svg");
        member.setName(FastGptUserConstants.TEAM_MEMBER_NAME);
        member.setRole(FastGptUserConstants.TEAM_MEMBER_NAME_NEW);
        member.setStatus(FastGptUserConstants.USER_STATUS);
        member.setDefaultTeam(true);
        member.setCreateAt(now);
        member.setUpdateTime(now);
        return mongoTeamMembersService.save(member);
    }

    private void cloneAndShareApp(String shareid, MongoTeamMembers teamMember, String username, SysUser sysUser) {
        MongoOutlinks outlink = mongoOutlinksService.findShareIdById(shareid);
        if (outlink == null) throw new IllegalStateException("分享链接不存在：" + shareid);

        MongoApps originApp = mongoAppsRepository.findById(outlink.getAppId());
        if (originApp == null) throw new IllegalStateException("应用不存在，appId=" + outlink.getAppId());

        originApp.setId(null);
        originApp.setTeamId(teamMember.getTeamId());
        MongoApps clonedApp = mongoAppsRepository.save(originApp);

        MongoOutlinks newOutlink = new MongoOutlinks();
        newOutlink.setAppId(clonedApp.getId());
        newOutlink.setName(username + "--" + outlink.getName());
        newOutlink.setTeamId(teamMember.getTeamId());
        newOutlink.setTmbId(teamMember.getId());
        newOutlink.setType("share");
        newOutlink.setShareId(shareIdprefix+sysUser.getUserId()+shareIdsuffix);
        newOutlink.setResponseDetail(true);
        newOutlink.setShowNodeStatus(true);
        newOutlink.setShowRawSource(true);
        newOutlink.setUsagePoints(0);

        MongoOutlinks.Limit limit = new MongoOutlinks.Limit();
        limit.setMaxUsagePoints(-1);
        limit.setQPM(100);
        newOutlink.setLimit(limit);

        mongoOutlinksService.save(newOutlink);

        SysUserShareid userShareid = new SysUserShareid();
        userShareid.setUserId(sysUser.getUserId());
        userShareid.setName(sysUser.getUserName());
        userShareid.setShareid(shareIdprefix+sysUser.getUserId()+shareIdsuffix);
        sysUserShareidService.insertSysUserShareid(userShareid);
    }



//    public static String generateRandomString() {
//        StringBuilder sb = new StringBuilder(LENGTH);
//        for (int i = 0; i < LENGTH; i++) {
//            int index = random.nextInt(CHARACTERS.length());
//            sb.append(CHARACTERS.charAt(index));
//        }
//        return sb.toString();
//    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }

        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);

        List<SysUser> sysUsers = userMapper.selectUserByuserIds(userIds);
        for (int i = 0; i < sysUsers.size(); i++) {
            SysUser sysUser = sysUsers.get(i);
            MongoUsers user = mongoUsersService.findByUsername(sysUser.getUserId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR);
            if(user!=null){
                MongoTeamMembers teamMembers = mongoTeamMembersService.findByUserId(user.getId());
                if (teamMembers == null) {
                    continue;
                }

                ObjectId teamId = teamMembers.getTeamId();
                try {
                    //删除shareid表
                    mongoOutlinksService.deleteByTeamId(teamId);
                    //删除应用表

                    mongoAppsRepository.deleteByTeamId(teamId);
                    //删除团队表

                    mongoTeamsService.deleteById(teamId);
                    //删除团队成员表

                    mongoTeamMembersService.deleteById(teamMembers.getId());

                    mongoUsersService.deleteById(user.getId());
                } catch (Exception e) {
                    log.error("删除用户 {} 失败：{}", sysUser.getUserId(), e.getMessage(), e);
                }

            }



        }
        int row = userMapper.deleteUserByIds(userIds);
        return row;
    }
    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    public static boolean containsChinese(String str) {
        if (str == null) {
            return false;
        }
        // 匹配中文字符的正则：[\u4e00-\u9fa5]
        return str.matches(".*[\\u4e00-\\u9fa5].*");
    }

    @Override
    @Transactional
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (CollectionUtils.isEmpty(userList)) {
            throw new ServiceException("导入用户数据不能为空！");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (SysUser user : userList) {
            try {

                if (containsChinese(user.getUserName())) {

                    throw new ServiceException("用户名不能包含中文字符！");
                }

                // 校验基础信息
                BeanValidators.validateWithException(validator, user);
                deptService.checkDeptDataScope(user.getDeptId());

                SysUser existingUser = userMapper.selectUserByUserName(user.getUserName());

                if (existingUser == null) {
                    // 新增
                    String initPassword = configService.selectConfigByKey("sys.user.initPassword");
                    user.setPassword(SecurityUtils.encryptPassword(initPassword));
                    user.setCreateBy(operName);
                    user.setCreateTime(new Date());
                    user.setRoleIds(new Long[]{user.getRoleId()});

                    userMapper.insertUser(user);
                    insertUserRole(user);
                    buildFastGptUser(user);

                    MongoMyUserOutlinksids outlinks = new MongoMyUserOutlinksids();
                    outlinks.setUserId(String.valueOf(user.getUserId()));
                    outlinks.setOutlinksid("shareChat-" + generateUniqueId());
                    mongoMyUserOutlinksidsService.save(outlinks);

                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 导入成功");
                } else if (isUpdateSupport) {
                    // 更新
                    checkUserAllowed(existingUser);
                    checkUserDataScope(existingUser.getUserId());

                    user.setUserId(existingUser.getUserId());
                    user.setUpdateBy(operName);
                    user.setUpdateTime(new Date());

                    userMapper.updateUser(user);

                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 更新成功");
                } else {
                    // 用户存在且不更新
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(user.getUserName()).append(" 已存在");
                }

            } catch (DuplicateKeyException e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：用户名已存在";
                failureMsg.append(msg);
                log.error(msg, e);
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    //设置合理的值
    public static String generateUniqueId() {
        long timestamp = System.currentTimeMillis(); // 生成时间戳
        String randomString = generateRandomString(22); // 生成随机字符串
        return  timestamp + "-" + randomString;
    }

    private static String generateRandomString(int length) {
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[length];
        random.nextBytes(bytes);
        return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes).substring(0, length);
    }
    /**
     * 获取未审核的用户列表
     *
     * @return
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnauditedUserList(SysUser user) {

        return userMapper.selectUnauditedUserList(user);
    }
}
